﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// This script handles the backlog of the dialogues.
/// </summary>

public class BacklogDisplayer : MonoBehaviour {
	
	public BackLogData backLogData;

//	void Awake()
//	{
//    }

	// Use this for initialization
	void Awake () { 
		Dialoguer.Initialize ();

		backLogData = GameObject.Find("DataManager").GetComponent<BackLogData>();
		Dialoguer.events.onTextPhase += onDisplayText;
		backLogData.LogText = GameObject.Find("LogText").GetComponent<UILabel>();

		backLogData.dialogues = new List<string> ();
		backLogData.names = new List<string> ();
	}
	
	// Update is called once per frame
	void Update () {

		 addLog();
		//logText.GetComponent<UILabel> ().text = allLines;
		backLogData.LogText.text = backLogData.allLines;
	} 

	void addLog()
	{
//		_mouseDetector.SetActive (true);
		/*for (int i = 0; i < _names.Count; i++)
			{
				if (i == 0)
					allLines = _names[i] + ": " + _dialogues[i] + "\n";
				else
					allLines += _names[i] + ": " + _dialogues[i] + "\n";
			}*/

		if(backLogData.dialogues.Count >= 200)
		{
			backLogData.dialogues.RemoveAt(0);
			backLogData.names.RemoveAt(0);
		}

		for(int i = 0; i < backLogData.names.Count; i++)
			{
				if(i == 0)
				backLogData.allLines = backLogData.names[i] + ": " + backLogData.dialogues[i] + "\n";
				else
				backLogData.allLines += backLogData.names[i] + ": " + backLogData.dialogues[i] + "\n";
			}
	}

	void onDisplayText(DialoguerTextData data){
		if(backLogData.dialogues.Count > 0)
		{
			//checks each dialogue in the list before adding the currently read dialogue in the script.
			for(int i = 0; i < backLogData.dialogues.Count; i++)
			{
				if(backLogData.dialogues[i].CompareTo(data.text) == 0) //int.compareTo(int) returns 0 if the values are exact.
					return;
			}
			/*_dialogues.Add(data.text);
			_names.Add(data.name);*/
			backLogData.addLine(data.name, data.text);
		}
		else
		{
			//automatically adds the first dialogue read
			/*_dialogues.Add (data.text);
			_names.Add (data.name);*/
			backLogData.addLine(data.name, data.text);
		}
	}

	private void SetLayerRecursively(GameObject obj, int newLayer)
	{
		if (null == obj)
		{
			return;
		}
		
		obj.layer = newLayer;
		
		foreach (Transform child in obj.transform)
		{
			if (null == child)
			{
				continue;
			}
			SetLayerRecursively(child.gameObject, newLayer);
		}
	}
}
